import React, { useEffect, useState } from 'react';
import './index.scss';
import { MyInput, MyButton, ConfirmDialog, ImagePreview } from '../../components';
import { useNavigate } from 'react-router-dom';
import { useAppSelector } from '../../utils/storeHook/storeHook';
import http from '../../utils/http';
import api from '../../api';
import { formateDate, formateRealDate, formatFileSize } from '../../utils';
import { message, Table, Tooltip, Upload, type TableProps, type UploadProps } from 'antd';
import {EyeOutlined, UploadOutlined, EditOutlined} from '@ant-design/icons';

type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];

interface User {
    user_id: string;
    username: string;
    email: string;
    avatar_id?: string;
    avatar_url?: string;
    bio: string;
    status: 'online' | 'idle' | 'dnd' | 'offline';
    currentActivity?: string;
    created_at: string;
    friendCount: number;
    serverCount: number;
    tags: string;
    // messageCount: number;
}

interface FileItem {
    key: React.Key;
    file_id: string;
    original_name: string;
    type: 'image' | 'pdf' | 'video' | 'audio' | 'other';
    size: number;
    channel_id: string;
    created_at: string;
    direct_chat_id: string;
    file_url: string;
    mime_type: string;
    stored_name: string;
    uploader_id: string;
}
const PersonalInfo = () => {
    const navigate = useNavigate()
    const curUserId = useAppSelector(state=>state.auth.user_id)

    
    const [fileTasks, setFileTasks] = useState<{[key: string]: {progress: number, file: File}}>({});

    const [messageApi, contextHolder] = message.useMessage()
    const [activeTab, setActiveTab] = useState<'profile' | 'files'>('profile');
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [editMode, setEditMode] = useState(false);
    const [previewVis,setPreviewVis] = useState(false)
    const [previewImgs,setPreviewImgs] = useState<string[]>(['https://linkchat.xingkdsite.top/assets/avatar-nqOiAI_u.jpg'])

    const [user, setUser] = useState<User>({
        user_id: 'string',
        username: 'string',
        email: 'string',
        bio: 'string',
        status: 'online',
        currentActivity: 'string',
        created_at: 'string',
        friendCount: 1,
        serverCount: 2,
        tags: JSON.stringify(['string']),
        // messageCount: 3,
    });
    const [filePagination, setFilePagination] = useState({
        pageCur:1,
        pageSize:10,
        total:0
    })
    const [files, setFiles] = useState<FileItem[]|[]>([]);
    const [formData, setFormData] = useState({
        username: user.username,
        email: user.email,
        bio: user.bio,
    });
    const [confirmDelete, setConfirmDelete] = useState({
        visible: false,
        fileId: '',
    });

    const fileColumns: TableProps<FileItem>['columns'] = [
        {
            title: '文件名',
            dataIndex: 'original_name',
            key: 'original_name',
            render: (text) => <div>{text}</div>,
        },
        {
            title: '上传日期',
            dataIndex: 'created_at',
            key: 'created_at',
            render: (date) => <div>{formateRealDate(date)}</div>,
        },
        {
            title: '大小',
            dataIndex: 'size',
            key: 'size',
            render: (size) => <div>{formatFileSize(size)}</div>,
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <div className='file-actions'>
                    <div className='file-action' onClick={() => downloadFile(record.file_url,record.original_name)}>
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                            <polyline points="7 10 12 15 17 10"/>
                            <line x1="12" y1="15" x2="12" y2="3"/>
                        </svg>
                    </div>
                    <div className='file-action' onClick={()=>{
                        setConfirmDelete({
                            visible:true,
                            fileId:record.file_id
                        })
                    }}>
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M3 6h18"/>
                            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                            <line x1="10" y1="11" x2="10" y2="17"/>
                            <line x1="14" y1="11" x2="14" y2="17"/>
                        </svg>
                    </div>
                </div>
            ),
        },
    ];

    // 选择需要有key属性
    const rowSelection: TableRowSelection<FileItem> = {
        selectedRowKeys,
        onChange: (newSelectedRowKeys: React.Key[])=>{
            setSelectedRowKeys(newSelectedRowKeys);
        },
    };
  
    const handleTabChange = (tab: 'profile' | 'files') => {
        setActiveTab(tab);
    };
    
    const handleEditClick = () => {
        setFormData({
            ...user
        });
        setEditMode(!editMode);
    };
  
    const handleInputChange = (value:string,id:string) => {
        setFormData(prev => ({
            ...prev,
            [id]: value
        }));
    };
  
    const handleSaveChanges = () => {
        setEditMode(false);
        http.post(api.auth.editUserInfo,{...formData}).then(()=>{
            getPersonalInfo()
        })
    };
  
    const handleCancelChanges = () => {
        setFormData({
            username: user.username,
            email: user.email,
            bio: user.bio,
        });
        setEditMode(false);
    };

    async function getPersonalInfo(){
        http.post(api.auth.getPersonalInfo,{user_id:curUserId}).then(res=>{
            setUser(res.data)
        })
    }

    async function getUserFileList(){
        http.post(api.file.getUserFileList,{...filePagination}).then(res=>{
            setFiles(res.data.fileList.map((file:FileItem)=>{
                file['key'] = file.file_id
                return file
            }))
            setFilePagination(prev=>({...prev,total:res.data.total}))
        })
    }

    function pageChange(pageCur:number,pageSize:number){
        setFilePagination(prev=>({...prev,pageCur,pageSize}))
    }

    async function deleteFile(){ 
        http.post(api.file.deleteFile,{file_id:confirmDelete.fileId}).then(()=>{
            getUserFileList()
            setConfirmDelete({fileId:'null',visible:false})
        })
    }

    async function downloadFile(url:string,filename:string){
        fetch(url)
            .then(response => response.blob())
            .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename || url.split('/').pop() || 'download';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        })
        .catch(error => console.error('下载失败:', error));
    }

    function downloadSelectedFiles(){
        const downloadPromises = selectedRowKeys.map(id => {
            const file = files.find(f => f.file_id === id);
            if (!file) {
                return Promise.reject(`File not found for ID: ${id}`);
            }
            return downloadFile(file.file_url, file.original_name);
        });
        Promise.all(downloadPromises).then(()=>{
            messageApi.success('下载完成')
        })
    }

    function deleteSelectedFiles(){ 
        const deletePromises = selectedRowKeys.map(id => 
            http.post(api.file.deleteFile, { file_id: id })
        );
        Promise.all(deletePromises).then(()=>{
            getUserFileList()
            messageApi.success('删除成功')
        })
    }

    // 启动文件上传
    const startFileUpload = async (file: File) => {
        // const taskId = uuidv4(); // 生成唯一任务ID
        const taskId = 6746546513
        const CHUNK_SIZE = 5 * 1024 * 1024;
        
        setFileTasks(prev => ({
            ...prev,
            [taskId]: { file, progress: 0 }
        }));
        
        try {
            // 1. 初始化上传
            const initRes = await http.post(api.file.init_upload, {
                file_name: file.name,
                size: file.size,
                mime_type: file.type,
                total_chunks: Math.ceil(file.size / CHUNK_SIZE),
            });
            
            const serverTaskId = initRes.data.task_id;
            
            // 2. 上传所有分片
            const chunks = createFileChunks(file, CHUNK_SIZE);
            let uploaded = 0;
            
            for (let i = 0; i < chunks.length; i++) {
                const formData = new FormData();
                formData.append('task_id', serverTaskId);
                formData.append('chunk_index', i.toString());
                formData.append('chunk', chunks[i].chunk);
                
                await http.post(api.file.upload_chunk, formData, {
                    headers: { 'Content-Type': 'multipart/form-data' },
                });
                
                // 更新进度
                uploaded++;
                const progress = Math.floor((uploaded / chunks.length) * 100);
                setFileTasks(prev => ({
                    ...prev,
                    [taskId]: {...prev[taskId], progress}
                }));
            }
            
            // 3. 完成上传
            const completeRes = await http.post(api.file.complete_upload, {
                task_id: serverTaskId
            });
            
            const fileInfo = completeRes.data;
            // onFileChange && onFileChange(fileInfo);
            
            // 完成上传，修改头像
            await http.post(api.auth.editUserInfo,{avatar_url:fileInfo.file_url})
            if(user.avatar_id) await http.post(api.file.deleteFile, { file_id: user.avatar_id })
            await getPersonalInfo()
        } catch (err) {
            messageApi.error('上传失败: ');
        } finally {
        // 清理任务
            setFileTasks(prev => {
                const newTasks = {...prev};
                delete newTasks[taskId];
                return newTasks;
            });
        }
    };
        // 创建文件分片
    const createFileChunks = (file: File, chunkSize: number) => {
        const chunks = [];
        let start = 0;
        
        while (start < file.size) {
            const end = Math.min(start + chunkSize, file.size);
            const chunk = file.slice(start, end);
            chunks.push({
                index: chunks.length,
                chunk
            });
            start = end;
        }
        
        return chunks;
    };

    const avatarProps: UploadProps={
        beforeUpload: (file) => {
            const max_size = 1024 * 1024 * 5
            const arrowType = ['png','jpeg','jpg','webp']
            let isPNG = false
            for(let key of arrowType){
                if(file.type.includes(key)){
                    isPNG = true
                    break
                }
            }
            if (!isPNG) {
                messageApi.error(`${file.name}不是图片文件`);
                return false || Upload.LIST_IGNORE
            }
            
            if(file.size > max_size){
                messageApi.error(`${file.name}文件过大:大于${max_size/1024/1024}MB`);
                return false || Upload.LIST_IGNORE;
            }
            startFileUpload(file)
            return false || Upload.LIST_IGNORE;
        },
    }

    useEffect(()=>{
        if(curUserId){
            getPersonalInfo()
            getUserFileList()
        }
    },[])

    useEffect(()=>{ 
        getUserFileList()
    },[filePagination.pageCur,filePagination.pageSize])
    return (
    <>
        {contextHolder}
        <ImagePreview images={previewImgs} visible={previewVis} onClose={()=>setPreviewVis(false)}></ImagePreview>
        <div className="personal_info">
            <div className='personal_back' onClick={()=>navigate(-1)}>返回</div>
            {/* 顶部固定信息 */}
            <div className="personal_profile_header">
                <div className="personal_profile_avatar">
                    {user.avatar_url ? (
                        <img loading='lazy' src={user.avatar_url} alt={user.username} />
                    ) : (
                        <div className="personal_userInfoDlg_avatar_placeholder">{user.username.charAt(0).toUpperCase()}</div>
                    )}
                    <div className='personal_avatar_upload'>
                        <Tooltip title="预览">
                            <div 
                                className='personal_avatar_preview' 
                                onClick={()=>{
                                    user.avatar_url && setPreviewImgs([user.avatar_url])
                                    setPreviewVis(true)
                                }}
                            >
                                <EyeOutlined />
                            </div>
                        </Tooltip>
                        <Tooltip title="上传新头像">
                            <Upload {...avatarProps}>
                                <div className='personal_avatar_upload_btn'>
                                        <UploadOutlined />
                                </div>
                            </Upload>
                        </Tooltip>
                    </div>
                </div>
                
                <h2 className="personal_profile_username">{user.username}</h2>
                
                <div className={`personal_profile_status status-${user.status}`}>
                    {user.status === 'online' ? '在线' : 
                    user.status === 'idle' ? '离开' : 
                    user.status === 'dnd' ? '请勿打扰' : '离线'}
                </div>
                
                <p className="personal_profile_bio">{user.bio}</p>
                
                <div className="personal_profile_stats">
                    <div className="personal_stat_item">
                        <div className="personal_stat_number">{user.friendCount}</div>
                        <div className="personal_stat_label">好友</div>
                    </div>
                    <div className="personal_stat_item">
                        <div className="personal_stat_number">{user.serverCount}</div>
                        <div className="personal_stat_label">频道</div>
                    </div>
                    {/* <div className="personal_stat_item">
                        <div className="personal_stat_number">{user.messageCount}</div>
                        <div className="personal_stat_label">消息</div>
                    </div> */}
                    <div className="personal_stat_item">
                        <div className="personal_stat_number">{filePagination.total}</div>
                        <div className="personal_stat_label">文件</div>
                    </div>
                </div>
            </div>
            
            {/* Tab 导航 */}
            <div className="personal_tabs">
                <button 
                    className={`personal_tab ${activeTab === 'profile' ? 'active' : ''}`}
                    onClick={() => handleTabChange('profile')}
                >
                    个人信息
                </button>
                <button 
                    className={`personal_tab ${activeTab === 'files' ? 'active' : ''}`}
                    onClick={() => handleTabChange('files')}
                >
                    已上传文件
                </button>
            </div>
            
            {/* 内容区域 */}
            <div className="personal_tab_content">
                {activeTab === 'profile' ? (
                <div className="personal_tab_pane active">
                    <h3 className="personal_section_title">
                        {editMode ? '编辑个人信息' : '个人信息'}
                        
                        {!editMode && (
                            <div className="personal_edit_btn">
                                <MyButton type='default' onClick={handleEditClick}>
                                    <EditOutlined />
                                    编辑
                                </MyButton>
                            </div>
                        )}
                    </h3>
                    
                    <div className="personal_form_grid">
                        <div className="personal_form_group">
                            <label>用户名</label>
                            {editMode ? (
                            <MyInput
                                placeholder='用户名' 
                                type="text" 
                                id='username'
                                value={formData.username}
                                onChange={handleInputChange}
                            />
                            ) : (
                            <div className="personal_form_static">{user.username}</div>
                            )}
                        </div>
                        
                        <div className="personal_form_group">
                            <label>邮箱地址</label>
                            {editMode ? (
                            <MyInput 
                                type="email" 
                                id='email'
                                placeholder='邮箱地址'
                                value={formData.email}
                                onChange={handleInputChange}
                            />
                            ) : (
                            <div className="personal_form_static">{user.email}</div>
                            )}
                        </div>
                        
                        <div className="personal_form_group">
                            <label>账号 ID</label>
                            <div className="personal_form_static">@{user.user_id}</div>
                        </div>
                        
                        <div className="personal_form_group">
                            <label>注册日期</label>
                            <div className="personal_form_static">{formateDate(user.created_at)}</div>
                        </div>
                        
                        <div className="personal_form_group full-width">
                            <label>个人简介</label>
                            {editMode ? (
                            <MyInput 
                                className="personal_form_control"
                                placeholder={user.bio ? '个人简介' : '不写简介也是一种个性'}
                                type='textarea'
                                id='bio'
                                value={formData.bio}
                                onChange={handleInputChange}
                                rows={3}
                            />
                            ) : (
                            <div className="personal_form_static">{user.bio ? user.bio : '不写简介也是一种个性'}</div>
                            )}
                        </div>
                    </div>
                    
                    {editMode && (
                    <>
                        <div className="personal_form_actions">
                            <MyButton type='default' onClick={handleSaveChanges}>
                                保存更改
                            </MyButton>
                            <MyButton type='guest' onClick={handleCancelChanges}>
                                取消
                            </MyButton>
                        </div>
                    </>
                    )}
                </div>
                ) : (
                <div className="personal_tab_pane active">
                    <h3 className="personal_section_title">
                        已上传文件
                        
                        {selectedRowKeys.length > 0 && 
                            <div className='personal_select_btns'>
                                <MyButton type='default' onClick={downloadSelectedFiles}>
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                                        <polyline points="7 10 12 15 17 10"/>
                                        <line x1="12" y1="15" x2="12" y2="3"/>
                                    </svg>
                                    <span>下载所选文件</span>
                                </MyButton>
                                <MyButton type='default' onClick={deleteSelectedFiles}>
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <path d="M3 6h18"/>
                                        <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                                        <line x1="10" y1="11" x2="10" y2="17"/>
                                        <line x1="14" y1="11" x2="14" y2="17"/>
                                    </svg>
                                    <span>删除所选文件</span>
                                </MyButton>
                            </div>
                        }
                    </h3>
                    
                    <div className="personal_files_table">
                        <Table<FileItem> 
                            rowSelection={rowSelection}
                            columns={fileColumns} 
                            dataSource={files} 
                            pagination={{
                                showSizeChanger: true,
                                defaultCurrent: filePagination.pageCur, 
                                pageSize: filePagination.pageSize,
                                total: filePagination.total,
                                onChange: pageChange
                            }}
                        />
                    </div>
                </div>
                )}
            </div>
        </div>
        <ConfirmDialog visible={confirmDelete.visible} onClose={()=>setConfirmDelete({
            visible:false,
            fileId:''
        })} onConfirm={deleteFile}/>
    </>
    );
};

export default PersonalInfo;